package com.lft10.sync;

/**
 * Function: 		A {@code UnsafeBuyTicket} object 演示不安全的买票.<br/>
 * Reason:   		线程不安全，会出现 0 或负数.<br/>
 * Date:            2021-01-27 20:20<br/>
 * <p>
 * Class Name:      UnsafeBuyTicket<br/>
 * Package Name:    com.lft10.sync<br/>
 * @author Laifengting / E-mail:laifengting@foxmail.com
 * @version 1.0.0
 * @since JDK 8
 */
public class UnsafeBuyTicket {
	public static void main(String[] args) {
		BuyTicket buyTicket = new BuyTicket();
		new Thread(buyTicket, "学生").start();
		new Thread(buyTicket, "老师").start();
		new Thread(buyTicket, "黄牛").start();
	}
}

class BuyTicket implements Runnable {
	// 票
	private int ticketNums = 10;
	// 线程循环外部停止标识位
	private boolean flag = true;
	
	@Override
	public void run() {
		// 买票
		while (flag) {
			buyTicket();
		}
	}
	
	/**
	 * synchronized 同步方法
	 */
	private synchronized void buyTicket() {
		// 判断票数大于0
		if (ticketNums <= 0) {
			flag = false;
			return;
		}
		// 模拟延时
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 买票
		System.out.println(Thread.currentThread().getName() + " 买到一张票，票号为：" + ticketNums--);
	}
	
}